package com.ruoyi.system.service.aggregation.impl;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.AliyunOSSConfig;
import com.ruoyi.common.config.AggregationConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.QrCodeUtil;
import com.ruoyi.common.utils.file.AliyunOSSUtils;
import com.ruoyi.system.domain.aggregation.AggQrcode;
import com.ruoyi.system.domain.aggregation.User;
import com.ruoyi.system.mapper.aggregation.AggQrcodeMapper;
import com.ruoyi.system.mapper.aggregation.UserMapper;
import com.ruoyi.system.service.aggregation.IQrCodeService;

/**
 * 二维码Service实现
 * 
 * @author ruoyi
 * @date 2025-01-01
 */
@Service
public class QrCodeServiceImpl implements IQrCodeService 
{
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private AggQrcodeMapper aggQrcodeMapper;
    
    @Autowired
    private AliyunOSSConfig ossConfig;
    
    @Autowired
    private AliyunOSSUtils ossUtils;
    
    @Autowired
    private AggregationConfig aggregationConfig;

    /**
     * 生成商家聚合二维码
     */
    @Override
    public String generateMerchantQrCode(Long merchantId) throws Exception
    {
        // 查询商家信息
        User merchant = userMapper.selectUserById(merchantId);
        if (merchant == null)
        {
            throw new Exception("商家不存在");
        }

        // 检查是否已有聚合码
        AggQrcode existing = aggQrcodeMapper.selectAggQrcodeByMerchantId(merchantId);
        
        // 临时注释：用于测试OSS功能，总是重新生成
        // if (existing != null && existing.getStatus() == 1)
        // {
        //     System.out.println("⚠️ 商家" + merchantId + "已有二维码，直接返回：" + existing.getQrCodeUrl());
        //     return existing.getQrCodeUrl();
        // }
        
        System.out.println("🔄 商家" + merchantId + " - 开始生成二维码（测试OSS）");

        // 二维码内容：App下载链接 + 商家绑定参数
        // 用户扫码后下载App，App自动绑定到该商家
        String appDownloadUrl = aggregationConfig.getApp().getDownloadUrl();
        String content = appDownloadUrl + "?merchantId=" + merchantId + "&from=qr";
        
        System.out.println("📱 生成聚合码内容：" + content);

        // 生成二维码文件
        String uploadPath = RuoYiConfig.getUploadPath();
        String fileName = "merchant_" + merchantId + "_" + System.currentTimeMillis() + ".png";
        String filePath = uploadPath + File.separator + "qrcode" + File.separator + fileName;

        // 创建目录
        File dir = new File(uploadPath + File.separator + "qrcode");
        if (!dir.exists())
        {
            dir.mkdirs();
        }

        // 生成二维码
        QrCodeUtil.generateQRCodeFile(content, filePath, 400, 400);
        
        // 保存到OSS或本地
        String qrCodeUrl;
        if (ossConfig != null && ossConfig.getEnabled())
        {
            System.out.println("✅ 商家码 - OSS已启用，开始上传到OSS...");
            // 上传到OSS
            FileInputStream fis = new FileInputStream(new File(filePath));
            String ossPath = "qrcode/" + fileName;
            qrCodeUrl = ossUtils.uploadFile(ossPath, fis);
            fis.close();
            
            System.out.println("✅ 商家码 - OSS上传成功：" + qrCodeUrl);
            
            // 删除本地临时文件
            new File(filePath).delete();
        }
        else
        {
            System.out.println("⚠️ 商家码 - OSS未启用，使用本地存储");
            // 本地存储
            qrCodeUrl = "qrcode/" + fileName;
        }

        // 保存到数据库
        if (existing == null)
        {
            // 新增记录
            AggQrcode aggQrcode = new AggQrcode();
            aggQrcode.setMerchantId(merchantId);
            aggQrcode.setMerchantName(merchant.getName());
            aggQrcode.setQrCodeUrl(qrCodeUrl);
            aggQrcode.setQrContent(content);
            aggQrcode.setScanCount(0);
            aggQrcode.setStatus(1);
            aggQrcode.setDeleted(0);
            aggQrcode.setCreateTime(new Date());
            aggQrcodeMapper.insertAggQrcode(aggQrcode);
        }
        else
        {
            // 更新记录
            existing.setQrCodeUrl(qrCodeUrl);
            existing.setQrContent(content);
            existing.setStatus(1);
            existing.setUpdateTime(new Date());
            aggQrcodeMapper.updateAggQrcode(existing);
        }

        return qrCodeUrl;
    }

    /**
     * 生成App下载二维码
     */
    @Override
    public String generateDownloadQrCode() throws Exception
    {
        // 二维码内容：App下载地址（可配置）
        String downloadUrl = "https://example.com/app/download";
        String content = downloadUrl;

        // 生成二维码文件
        String uploadPath = RuoYiConfig.getUploadPath();
        String fileName = "app_download_" + System.currentTimeMillis() + ".png";
        String filePath = uploadPath + File.separator + "qrcode" + File.separator + fileName;

        // 创建目录
        File dir = new File(uploadPath + File.separator + "qrcode");
        if (!dir.exists())
        {
            dir.mkdirs();
        }

        // 生成二维码
        QrCodeUtil.generateQRCodeFile(content, filePath, 400, 400);
        
        // 保存到OSS或本地
        String qrCodeUrl;
        if (ossConfig != null && ossConfig.getEnabled())
        {
            System.out.println("✅ 下载码 - OSS已启用，开始上传到OSS...");
            // 上传到OSS
            FileInputStream fis = new FileInputStream(new File(filePath));
            String ossPath = "qrcode/" + fileName;
            qrCodeUrl = ossUtils.uploadFile(ossPath, fis);
            fis.close();
            
            System.out.println("✅ 下载码 - OSS上传成功：" + qrCodeUrl);
            
            // 删除本地临时文件
            new File(filePath).delete();
        }
        else
        {
            System.out.println("⚠️ 下载码 - OSS未启用，使用本地存储");
            // 本地存储
            qrCodeUrl = "qrcode/" + fileName;
        }

        return qrCodeUrl;
    }

    /**
     * 查询聚合码列表
     */
    @Override
    public List<AggQrcode> selectAggQrcodeList(AggQrcode aggQrcode)
    {
        return aggQrcodeMapper.selectAggQrcodeList(aggQrcode);
    }

    /**
     * 查询聚合码详情
     */
    @Override
    public AggQrcode selectAggQrcodeById(Long id)
    {
        return aggQrcodeMapper.selectAggQrcodeById(id);
    }

    /**
     * 根据商家ID查询聚合码
     */
    @Override
    public AggQrcode selectAggQrcodeByMerchantId(Long merchantId)
    {
        return aggQrcodeMapper.selectAggQrcodeByMerchantId(merchantId);
    }

    /**
     * 记录扫码
     */
    @Override
    public void recordScan(Long merchantId)
    {
        aggQrcodeMapper.incrementScanCount(merchantId);
    }
}

